package com.hr.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hr.domain.dto.AiHouseDTO;
import com.hr.domain.dto.HouseDTO;
import com.hr.domain.po.House;
import com.hr.domain.query.HousePageResult;
import com.hr.domain.query.HouseQueryParams;
import com.hr.domain.vo.AiHouseVO;
import com.hr.domain.vo.HouseVO;
import com.hr.mapper.HouseFacilityMapper;
import com.hr.mapper.HouseImageMapper;
import com.hr.service.HouseService;
import com.hr.mapper.HouseMapper;
import com.hr.service.RedisHouseService;
import com.hr.utils.Result;
import com.hr.utils.UserContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86150
* @description 针对表【house(房源表)】的数据库操作Service实现
* @createDate 2025-09-23 14:20:06
*/
@Slf4j
@Service
@AllArgsConstructor
public class HouseServiceImpl implements HouseService{

    private final HouseMapper houseMapper;

    private final HouseImageMapper houseImageMapper;

    private final HouseFacilityMapper houseFacilityMapper;

    private final RedisHouseService redisHouseService;

    /**
     * 获取房屋列表
     * @return List<HouseVO>
     */
    @Override
    public List<HouseVO> getHouseList() {
        return houseMapper.getHouseList();
    }

    /**
     * 获取房屋分页列表
     * @param queryParams 查询参数
     * @return HousePageResult
     */
    @Override
    public HousePageResult getHousePageList(HouseQueryParams queryParams) {
        //开始分页
        PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
        //传入分页参数以及分页查询条件
        List<HouseVO> houseList = houseMapper.getHousePageList(queryParams);
        //转换为Page<HouseVO>类型
        Page<HouseVO> page = (Page<HouseVO>) houseList;
        //返回结果
        return new HousePageResult(page.getTotal(), page.getResult());
    }

    /**
     * 更新房屋状态
     * @param id 房屋id
     * @param status 状态
     * @return String
     */
    @Override
    public String updateHouseStatus(Long id, Integer status) {
        int row = houseMapper.updateHouseStatus(id, status);

        return row > 0 ? "更新房屋状态成功" : "更新房屋状态失败";
    }

    @Override
    public String publishHouse(HouseDTO houseDTO) {
        //房屋的地址要求时唯一的
        List<House> addressList = houseMapper.selectAllAddress();
        for (House house : addressList) {
            if (house.getAddress().equals(houseDTO.getAddress())) {
                return "房屋地址已存在";
            }
        }
        House house = new House();
        BeanUtils.copyProperties(houseDTO, house);
        //设置状态为待审核--1上架，2下架
        house.setStatus(0);

        house.setPublishTime(LocalDateTime.now());
        //TODO 管理端输入时可自行输入，但当房东输入时就要通过线程获取当前登录用户id
        //判断当前是否为管理员
        /*if ()*/
        /*house.setLandlordId(1L);*/
        // 获取当前用户
        Long userId = UserContext.getUserId();
        Integer roleId = UserContext.getRoleId();

        if (userId == null || roleId == null) {
            return "用户未登录或信息异常";
        }

        // 权限判断
        if (roleId == 2) { // 房东
            house.setLandlordId(userId);
        } else if (roleId == 3) { // 管理员
            house.setLandlordId(houseDTO.getLandlordId() != null ? houseDTO.getLandlordId() : userId);
        } else {
            return "权限不足，普通用户无法发布房源";
        }


        int row = houseMapper.insert(house);
        return row > 0 ? "发布房屋成功" : "发布房屋失败";

    }

    /**
     * 删除房屋信息
     * @param id 房屋id
     * @return String
     */
   /* @Override
    public String deleteHouseById(Integer id) {
        int row = houseMapper.deleteHouseById(id);
        //删除房屋信息后也需要删除房屋图片
        //第一步：根据房屋id获取房屋图片id
        List<Integer> houseImageIdList = houseImageMapper.getHouseImageId(Long.valueOf(id));
        //第二部：根据图片id删除房屋图片
        int deleteImageRow = houseImageMapper.deleteHouseImageBatch(houseImageIdList);
        if (deleteImageRow <= 0){
            return "删除房屋信息失败，房屋关联图片无法删除！";
        }
        //删除房屋周边配套信息
        //第一步：根据房屋id获取房屋周边配套id
        List<Integer> houseFacilityIdList = houseFacilityMapper.getHouseFacilityId(Long.valueOf(id));
        //第二部：根据图片id删除房屋周边配套信息
        int deleteFacRow = houseFacilityMapper.deleteHouseFacilityBatch(houseFacilityIdList);
        if (deleteFacRow <= 0){
            return "删除房屋信息失败，房屋关联周边配套无法删除！";
        }
        return row > 0 ? "删除房屋信息成功" : "删除房屋信息失败";
    }*/
    //缺少事务管理，可能会导致事务删除异常
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteHouseById(Integer id) {
        Long houseId = id.longValue();

        try {
            // 先清除缓存
            redisHouseService.clearHouseCache(houseId);


            // 删除图片
            List<Integer> imageIds = houseImageMapper.getHouseImageId(houseId);
            if (imageIds != null && !imageIds.isEmpty()) {
                int imgRows = houseImageMapper.deleteHouseImageBatch(imageIds);
                if (imgRows <= 0) {
                    return Result.error("删除房屋图片失败");
                }
            }

            // 删除配套设施
            List<Integer> facilityIds = houseFacilityMapper.getHouseFacilityId(houseId);
            if (facilityIds != null && !facilityIds.isEmpty()) {
                int facRows = houseFacilityMapper.deleteHouseFacilityBatch(facilityIds);
                if (facRows <= 0) {
                    return Result.error("删除房屋配套设施失败");
                }
            }

            // 删除主表
            int houseRows = houseMapper.deleteHouseById(id);
            if (houseRows <= 0) {
                return Result.error("未找到要删除的房源");
            }

            return Result.success("删除房屋信息成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统异常：" + e.getMessage());
        }
    }

    /**
     * 获取所有房屋朝向
     * @return List<String>
     */
    @Override
    public List<String> selectAllOrientation() {
        List<String> orientationList = houseMapper.selectAllOrientation();
        // 使用Stream API去除重复的朝向数据
        return orientationList.stream()
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 更新房屋租价
     * @param id 房屋id
     * @param rent 租价
     * @return String
     */
    @Override
    public String updateHouseRent(Long id, Double rent) {
        int row = houseMapper.updateHouseRent(id, rent);
        return row > 0 ? "更新房屋租价成功" : "更新房屋租价失败";
    }

    /**
     * 获取所有房屋id
     * @return List<Long>
     */
    @Override
    public List<Long> getAllHouseId() {
        List<Long> houseIdList = houseMapper.getAllHouseId();
        if (houseIdList.isEmpty()){
            return null;
        }
        return houseIdList;
    }

    /**
     * 编辑房屋信息
     * @param houseDTO
     * @return String
     */
    @Override
    public String editHouse(HouseDTO houseDTO) {
        House house = new House();
        BeanUtils.copyProperties(houseDTO, house);
        int row = houseMapper.update(house);

        // 清除缓存
        if (row > 0) {
            redisHouseService.clearHouseCache(houseDTO.getId());
        }


        return row > 0 ? "更新房屋信息成功" : "更新房屋信息失败";
    }

    /**
     * 根据id获取房屋信息
     * @param id
     * @return HouseVO
     */
    @Override
    public HouseVO getHouseById(Long id) {
        HouseVO houseVO = houseMapper.getHouseById(id);
        if (houseVO == null){
            return null;
        }
        return houseVO;
    }

    /*@Override
    @Transactional(rollbackFor = Exception.class)
    public String batchDeleteHouse(List<Long> ids) {
        if (ids == null || ids.isEmpty()){
            return "请选择要删除的房源";
        }
        try {
             int deletedBatchHouseRows = houseMapper.deleteBatchHouse(ids);
             if (deletedBatchHouseRows <= 0){
                 log.error("批量删除不完全，期望删除 {} 条，实际删除 {} 条", ids.size(), deletedBatchHouseRows);
                 return "部分删除失败";
             }
             return "批量删除成功";
        }catch (Exception e){
            log.error("批量删除异常：{}", e.getMessage());
            throw new RuntimeException("批量删除异常", e);
        }
    }*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchDeleteHouse(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return "请选择要删除的房源";
        }

        // 记录成功和失败数量
        int successCount = 0;
        int failCount = 0;
        StringBuilder failReasons = new StringBuilder();

        for (Long id : ids) {
            try {
                // ✅ 复用单条删除逻辑（包含事务、图片、设施删除）
                Result result = deleteHouseById(id.intValue());

                if ("1".equals(result.getCode()) || "success".equals(result.getMsg())) {
                    successCount++;
                } else {
                    failCount++;
                    failReasons.append("ID=").append(id).append("失败：").append(result.getMsg()).append("; ");
                }
            } catch (Exception e) {
                failCount++;
                failReasons.append("ID=").append(id).append("异常：").append(e.getMessage()).append("; ");
                log.error("删除房屋ID={}时发生异常", id, e);
            }
        }

        // 返回结果汇总
        if (failCount == 0) {
            return "批量删除成功，共删除 " + successCount + " 条房源";
        } else {
            log.error("批量删除部分失败：成功{}条，失败{}条，原因：{}", successCount, failCount, failReasons);
            return "部分删除失败，成功" + successCount + "条，失败" + failCount + "条：" + failReasons;
        }
    }

    /**
     * 获取房屋详情信息
     *
     * @param aiHouseDTO
     * @return AiHouseVO
     */
    @Override
    public List<AiHouseVO> getHouseDetailForAI(AiHouseDTO aiHouseDTO) {
        if (aiHouseDTO == null){
            return null;
        }
        return houseMapper.getHouseDetailsForAi(aiHouseDTO);
    }
}




